﻿using System;
using System.Data;
using System.Collections;
using System.Collections.Specialized;

using Common;

using Castle.Core.Interceptor;
using Castle.DynamicProxy;

namespace com.globalwave.a8ext
{
    /// <summary>
    /// Reward 的摘要说明
    /// </summary>
    public class RewardService : BaseService
    {
        private static NameValueCollection whereMap = null;
        private const string TABLE_NAME = "a8ext_Reward";

        public RewardService()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        public RewardService(BaseService other)
            : base(other) 
        {
        }
        virtual public DataSet query(
                NameValueCollection criterion,
                int pageIndex,
                int pageSize,
             string orderString)
        {
            if (criterion.Get("pid") == null)
            {
                throw new BaseException("E000001", "参数错误");
            }
            else {
                criterion["@pid"] = criterion.Get("pid");
                criterion.Remove("pid");
            }

            string sql = RewardCriterion.GET_ALL_BY_PID ;


            if (criterion.Get("sid") != null)
             {
                 if ("".Equals(criterion.Get("sid")))
                 {
                     criterion.Remove("sid");
                 }
                 else
                 {
                     criterion["@sid"] = criterion.Get("sid");
                     criterion.Remove("sid");

                     sql += " and r.sid=? ";
                 }
            }

            DataSet result = dao.query(sql , pageIndex, pageSize, criterion, orderString == null ? " order by eff_date " : orderString, "Reward");

            return result;
        }

        virtual public int create(NameValueCollection reward)
        {
            if (reward.Get("pid") == null)
            {
                throw new BaseException("E000001", "参数错误");
            }

            int id = dao.insertTable(TABLE_NAME, reward);
            reward.Add("reward_id", id.ToString());
            return id;
        }

        virtual public int update(NameValueCollection reward)
        {
            NameValueCollection criterion = new NameValueCollection();
            string id = reward.Get("reward_id");

            criterion.Add("reward_id", id);

            reward.Remove("reward_id");

            int result = dao.updateTable(TABLE_NAME, reward, criterion);

            reward.Add("reward_id", id);

            return result;
        }

        virtual public int delete(NameValueCollection criterion)
        {
            if (criterion.Get("reward_id") != null)
            {
                throw new BaseException("E000001", "参数错误");
            }
            // delete cascade 
            //dao.deleteTable(TABLE_BULLETIN, criterion);
            //dao.deleteTable(TABLE_TOPIC, criterion);
            
            return dao.deleteTable(TABLE_NAME, criterion);

        }

        virtual public void deleteAll(string[] rewardIds)
        {
            if (rewardIds == null || rewardIds.Length == 0)
            {
                throw new BaseException("", "parames");
            }

            NameValueCollection criterion = new NameValueCollection();
            foreach (string rewardId in rewardIds)
            {
                criterion.Add("reward_ids", rewardId);
            }

            // delete cascade
            //dao.deleteTable(TABLE_BULLETIN, criterion);
            //dao.deleteTable(TABLE_TOPIC, criterion);

            dao.deleteTable(TABLE_NAME, criterion);

        }

        virtual public IList queryEmployeeReward(string employee_id, string date_start, string date_end)
        {
            IList result = new ArrayList();
            Hashtable reward = null;

            decimal reward_money_all = 0;
            decimal deduct_all = 0;
            decimal total_all = 0;
            decimal cost_all = 0;
            decimal gain_all = 0;

            NameValueCollection employeeParams = new NameValueCollection();
            employeeParams["@FullName"] = employee_id ;
            employeeParams["@UserCode"] = employee_id ;

            DataSet employeeDS = dao.query("select * from pub_etype where FullName=? or UserCode=? ", employeeParams,"Employee");
            if (employeeDS.Tables[0].Rows.Count != 1) {
                throw new BaseException("E810001", "没有找到唯一的员工！");
            }
            DataRow employee = employeeDS.Tables[0].Rows[0];
            string sid = U.getStringValue(employee["SID"]);

            DataSet billTypeDs = dao.queryTable("scm_billtype", null);

            foreach (DataRow billType in billTypeDs.Tables[0].Rows)
            {
                if (!C.YES.Equals(billType["is_reward_type"]))
                {
                    continue;
                }

                decimal deduct_percentage = 0;
                decimal reward_navigate = 1;
                string reward_relate_product = C.NO;
                string tableName = null;

                deduct_percentage = (decimal)billType["deduct_percentage"];
                reward_navigate = (decimal)billType["reward_navigate"];
                reward_relate_product = U.getStringValue(billType["reward_relate_product"]);
                tableName = U.getStringValue(billType["DetailTableName"]);

                NameValueCollection pars = new NameValueCollection();
                pars["eid"] = employee["_id"].ToString();
                pars["billdate_start"] = date_start;
                pars["billdate_end"] = date_end;

                DataSet detailDs = dao.queryTable(tableName, pars);

                foreach (DataRow detailRow in detailDs.Tables[0].Rows)
                {
                    reward = new Hashtable();
                    decimal total_ = (decimal)detailRow["TotalMoney"];
                    decimal cost_ = U.getDecimalValue(detailRow,"CostMoney", new decimal(0));
                    decimal quantity = U.getDecimalValue( detailRow,"QTy" ,new decimal(0)) ;
                    string billDate = ((DateTime)detailRow["BillDate"]).ToShortDateString() ;

                    decimal percentage = deduct_percentage;
                    string pid = U.getStringValue(detailRow,"pid", null);
                    // 计算直奖
                    if (pid != null && C.YES.Equals(reward_relate_product))
                    {
                        string product_name = "";
                        NameValueCollection productParams = new NameValueCollection();
                        productParams["_id"] = pid;
                        DataSet productDS = dao.queryTable("pub_ptype", productParams);

                        DataRow product = null;
                        if (productDS.Tables[0].Rows.Count > 0)
                        {
                            product = productDS.Tables[0].Rows[0];
                            product_name = U.getStringValue(product["FullName"]) ;
                            reward.Add("product_name", product_name);
                        }

                        NameValueCollection rewardParams = new NameValueCollection() ;
                        rewardParams.Add("@1", sid);
                        rewardParams.Add("@2", pid);
                        rewardParams.Add("@3", billDate);
                        rewardParams.Add("@4", billDate);

                        DataSet rewardDS = dao.query("select * from a8ext_reward where sid=? and pid=? and eff_date<=? and exp_date>=?",rewardParams,null) ;
                        if (rewardDS.Tables[0].Rows.Count != 1)
                        {
                            throw new BaseException("E810002","产品[" + product_name + "]奖赏配置不正配！");
                        }

                        DataRow rewardConfig = rewardDS.Tables[0].Rows[0] ;
                        percentage = (decimal)rewardConfig["deduct_percentage"];

                        if ((decimal)detailRow["Price"] >= (decimal)rewardConfig["min_reward_price"])
                        {
                            decimal reward_money =((decimal)rewardConfig["reward_money"]) * quantity ;
                            reward_money_all = reward_money_all + reward_money;
                            reward.Add("reward_money", System.Decimal.Round(reward_money,2));
                        }
                        else {

                            reward.Add("reward_money", 0);
                        }
                    }

                    total_all += total_;
                    cost_all += cost_;

                    reward.Add("total_", System.Decimal.Round(total_, 2));
                    reward.Add("cost_", System.Decimal.Round(cost_, 2));
                    decimal gain_ = (total_ - cost_);
                    decimal deduct_ = gain_ * percentage * reward_navigate/100 ;
                    deduct_all += deduct_;
                    gain_all += gain_;
                    reward.Add("deduct_", System.Decimal.Round(deduct_, 2));
                    reward.Add("gain_", System.Decimal.Round(gain_, 2));
                    reward.Add("bill_date", billDate);
                    reward.Add("bill_code", U.getStringValue(detailRow["BillCode"]));
                    reward.Add("billtype_name", billType["FullName"].ToString());
                    reward.Add("remark_", U.getStringValue(detailRow["Comment"]));
                    reward.Add("quantity_", System.Decimal.Round(quantity,0));
                    result.Add(reward);
                }
            }

            reward = new Hashtable();
            result.Add(reward);

            reward = new Hashtable();
            reward.Add("billtype_name", "总计：");
            reward.Add("total_", System.Decimal.Round(total_all, 2));
            reward.Add("cost_", System.Decimal.Round(cost_all, 2));
            reward.Add("deduct_", System.Decimal.Round(deduct_all, 2));
            reward.Add("gain_", System.Decimal.Round(gain_all, 2));
            reward.Add("reward_money", System.Decimal.Round(reward_money_all,2));
            result.Add(reward);

            return result;
        }



        public NameValueCollection getWhereConfigMap()
        {
            if (whereMap != null)
            {
                return whereMap;
            }

            whereMap = new NameValueCollection();

            whereMap.Add("reward_ids", " reward_id in (@reward_ids) ");
            whereMap.Add("billdate_start", " billdate >= ? ");
            whereMap.Add("billdate_end", " billdate <= ? ");

            return whereMap;
        }

        public static RewardService getInstance()
        {

            ProxyGenerator generator = new ProxyGenerator();

            return generator.CreateClassProxy<RewardService>(new TransactionInterceptor());

        }
    }


    public class RewardCriterion
    {
        public const string GET_ALL_BY_PID ="select r.*,s.fullname as subsite_name from a8ext_reward r, pub_subsite s where r.sid=s._id and r.pid=?";
    }
}
